$(document).ready(function() {

    $(".carePeople").click(function() {
        var careTxt = $(".carePeople").html();
        if (careTxt === "+关注") {
            $(".carePeople").html("取消关注");
        } else {
            $(".carePeople").html("+关注");
        }
    });
    console.log($(".modalDialog").width());
    // 模态框居中
    /*var windowWidth = $(window).width();
    console.log(windowWidth);
    if(windowWidth < 768) {
        console.log($(".modalBody").height());
        console.log($(".modalBody").width() /2);
        $(".modalRow").height($(".modalBody").width() /2 + "px");
    }*/
    // var marginL = ($(window).width() - $(".modalDialog").width()) / 2 + 'px';
    var marginL = 0.15 * $(window).width();
    var width = 0.7* $(window).width();
    console.log(width);
     $('.modalDialog').css("width", width);
    console.log(marginL);
    var marginT = ($(window).height() - $(".modalDialog").height()) / 2 + 'px';
    $('.modalDialog').css("margin-top", marginT);
    $('.modalDialog').css("margin-left", marginL);
    $('.panel-a img').click(function() {
        var img = $(this).attr("src");
        console.log(img);
        $('.modalImg').attr("src", img);

        // var marginL = ($(window).width() - 1200) / 2 + 'px';
        var marginT = ($(window).height() - 600) / 2 + 'px';
        var marginL = 0.15 * $(window).width();
        $('.modalDialog').css("margin-top", marginT);
        $('.modalDialog').css("margin-left", marginL);
        console.log(marginT);

        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        if(windowWidth < 768) {
            $(".modal-img, .modal-img img, .modal-other").css("height",(windowHeight/2) + 'px');
            $(".modal-img, .modal-img img, .modal-other").css("width",(windowWidth * 0.8) + 'px');  
        }
        
    });
    $('#signin-button,.btn').click(function() {
        var marginL = ($(window).width() - 600) / 2 + 'px';
        // $('.modal-dialog').css("margin-left", marginL);
    });

    //切换模式查看图片
    $(".view-grid").on("click",function() {
        $(".thumbs").addClass("active");
        $(".community-panel").hide();
    });
    $(".view-straight").on("click",function() {
        $(".community-panel").show();
        $(".thumbs").removeClass("active");
    });

    //照片详情、点赞和评论的模态框
    $(".community-mainPhotos").on("click",function() {
        var cheight = $(this).height();
        var cwidth = $(this).width();
        console.log((cwidth/cheight)*600);
        if(cwidth > cheight) {
            $(".modalImg").css("width", 600 );
            $(".modalImg").css("height", (cheight / cwidth) * 600 );
        }
        else {
            $(".modalImg").css("height", 600 );
            $(".modalImg").css("width", (cwidth / cheight) * 600 );
        }
        // $(".modal-other").css("height",cheight * 0.8);
        // $(".modalImg").css("margin-top",cheight * 0.8 * 0.1);
    });
    $('.comment-btn').click(function() {
        var comment = $('.comment-number').text();
        var commentText = $('#commentText').val();
        console.log(typeof commentText);
        if (commentText !== "") {
            $('.comment-number').html(++comment);
            console.log(commentText);
        }
    });
    $('.btn-love').click(function() {
        var text = $('.icon-number').text();
        $('.icon-number').html(++text);
        $('.heart').removeClass('glyphicon glyphicon-heart-empty');
        $('.heart').addClass('glyphicon glyphicon-heart');
    });
    $(".change-btn").click(function() {
        $(".word").hide();
        $(".comment").hide();
    });
    $('.publish-word').click(function() {
        var text = $('.icon-numb').text();
        $('.icon-numb').html(++text);
        $(".comment").hide();
    });
    $('.word').on('click',function(){
        var firstSpan = $(this).find("span:first-child");
        if(firstSpan.css("display") == "none"){
            $(this).find('div').hide(300);
            firstSpan.css("display","inline-block");
            firstSpan.next().css("display","none");
        } else {
            $(this).find('div').show(300);
            firstSpan.css("display","none");
            firstSpan.next().css("display","inline-block");
        }
        
    });
    $(".presentation-comment").on('click',function(){
        var list = $(".commentList");
        var listItem = $(".commentList").children('li');
        console.log(listItem.length);
        console.log(listItem);
        if(listItem.length < 5) {
            $(".commentList").show(300);
            $(".more").css("display","none");
        } else if(listItem.length >= 6){
            var i = 0;
            list.show(100);
            listItem.each(function(i){
                console.log(this);
                $(this).show(200);
                i++;
                if(i == 6) return false;
            });
            $(".more").on('click',function(){
                $(this).hide();
                var i = 6;
                listItem.each(function(i){
                console.log(this);
                $(this).show(200);
                i++;
                });
            });
        }
    });
    $(window).resize(function(){
        var width = $(window).width() * 0.7;
        var height = $(window).height() * 0.8;
        console.log("aaaa");
        $(".modalBody").css("width",width);
        // var marginL = ($(window).width() - $(".modalBody").width()) / 2;
        var marginL = 0.15 * $(window).width();
        var marginT = ($(window).height() - $(".modalBody").height()) / 2;
        console.log(marginL);
        $('.modalDialog').css("margin-top", marginT);
        $('.modalDialog').css("margin-left", marginL);
        $(".modalContent").css("width",width);
        // $(".modalBody").css("width",width);
        $(".modalRow").css("width",width);
        $(".modal-img").css("width",(width - 1) * 0.75);
        $(".modal-other").css("width",(width -1)* 0.25);
    });    
    //图片验证
    $("#input-file").on("change",function(){
        var filePath = $("#input-file").val();
        var formatStart = filePath.lastIndexOf(".");
        var format = filePath.substring(formatStart).toUpperCase();
        console.log(filePath);
        console.log(format);
            if(format != ".BMP" && format != ".PNG" && format != ".GIF" && format != ".JPG" && format != ".JPEG") {
                $("#errMsg").text("图片限于bmp,png,gif,jpeg,jpg格式");
                $("#submitImg").attr("disabled","disabled");
            } else {
                $("#errMsg").text("");
                $("#submitImg").removeAttr("disabled");
                console.log($("#submitImg"));
            }
        var fileSize = this.files[0].size;
        var size = fileSize / (1024 * 1024);
        console.log(fileSize);
        console.log(size);
        var maxSize = 100;
        if(size > maxSize) {
            $("#errMsg").text("图片不能超过 100 MB");
            $("#submitImg").attr("disabled","disabled"); 
        }
    });
    //是否升级为会员
    $('#IsMember').click(function() {
        if($('#IsMember').is(':checked')) {
            $('.upto-member').show();
        }
        else {
            $('.upto-member').hide();
        }
    })
    // 手机验证//
    $(".phone-num").blur(function() {
        var v = this.value;
        var a = /^0?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
        if (v.length != 11 || !v.match(a)) {
            $(this).next().show();
        } else {
            $(this).next().hide();
        }
    });
    //密码验证//
    $(".password").blur(function() {
        var v = this.value;
        if (v.length < 6 || v.length > 16) {
            $(this).next(".error").show();
        } else {
            $(this).next(".error").hide();
        }
    });
    $(".password-again").blur(function() {
        var v1 = $(this).val();
        var v2 = $(".password").val();
        if (v1 != v2) {
            $(this).next(".error").show();
        } else {
            $(this).next(".error").hide();
        }
    });
    //表单重置// 
    document.getElementById('loginClose').onclick = function() {
        var a = $("#remenber").is(':checked');
        if (a) {
            document.getElementsByClassName('reset')[0].reset();
            $('.error').hide();
            $('.login-alert-success,.login-alert-danger,.signup-alert-success,.signup-alert-danger').hide();
        } else {
            document.getElementsByClassName('reset')[0].reset();
            document.getElementsByClassName('reset')[1].reset();
            $('.error').hide();
            $('.login-alert-success,.login-alert-danger,.signup-alert-success,.signup-alert-danger').hide();
        }
    }
    // 验证码倒计时
    var wait = 60;

    function time(o) {
        if (wait == 0) {
            o.removeAttribute("disabled");
            o.value = "获取验证码";
            wait = 60;
        } else {
            o.setAttribute("disabled", true);
            o.value = "重新发送(" + wait + ")";
            wait--;
            setTimeout(function() {
                    time(o);
                },
                1000)
        }
    }
    $(".replace").on("click",function() {
        $("#input-file").click();
    });
    /*$("#input-file").change(function() {
        var val = $("#input-file").val();
        var a = new RegExp('[^/\\\\]+$');
        var b = a.exec(val);
        $("#publish-img").attr("src", "images/" + b[0]);
    });*/

    $("#useredit").on('click', function(){
        $(".basic-view").hide();
        $(".basic-write").fadeIn();
        $("#useredit").hide();
        $("#usersave").show(0,function(){
            $(this).css("display","inline-block");
        });
    });
    $("#usersave").on('click',function(){
        $(".basic-write").hide();
        $(".basic-view").fadeIn();
        $("#usersave").hide();
        $("#useredit").show();
    });
    $("#contactedit").on('click', function(){
        $(".contact-view").hide();
        $(".contact-write").fadeIn();
        $("#contactedit").hide();
        $("#contactsave").show(0,function(){
            $(this).css("display","inline-block");
        });
    });
    $("#contactsave").on('click',function(){
        var mail = $("#mail").val();
        var qq = $('#qq').val();
        var filter  =  /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
        var qq_filter = /^\d{5,10}$/;
        var filter_result = filter.test(mail) && qq_filter.test(qq);
        console.log(filter_result);
        // console.log(mail);
        if(filter_result || mail == "" || qq == ""){
            $(".contact-write").hide();
            $(".contact-view").fadeIn();
            $("#contactsave").hide();
            $("#contactedit").show();
            return true; 
        } else {
            alert('您的电子邮件或 QQ 的格式不正确');
            return false; 
        }
    });
    // 教育页面
    $(".edu-item--detail").on('click',function() {
        $(this).hide();
        $(this).next().show();
    });
    $(".edu-itemBtn--hide").on('click',function() {
        $(".edu-item--more").hide();
        $(".edu-item--detail").show();
    });
    // 展览页面
    $(".exb-item--detail").on('click',function() {
        $(this).hide();
        $(this).next().show();
    });
    $(".exb-itemBtn--hide").on('click',function() {
        $(".exb-item--more").hide();
        $(".exb-item--detail").show();
    });

    //后台接口//
    //获取验证码//
    $("#sentMessage").click(function() {
        var mobile = $('.phone-num').val();
        console.log(mobile);
        //组装数据包
        var data = {
            mobile: mobile
        };
        if(mobile) {
            $.ajax({
                url: 'http://mobile.goamob.com/index.php/User/reg?act=get_captcha',
                method: 'post',
                dataType: 'json',
                data: data,
                success: function(data) {
                    console.log(data);
                    if(data.code == 1) {
                        alert(data.message);
                    } else {
                        time(document.getElementById("sentMessage"));
                    }
                },
                error: function(data) {
                    alert("获取验证码失败，请重新获取");
                }
            });
        } else {
            alert("手机号不能为空");
        }
    });
    //注册
    // var isValid = false;
    $('.btn-signin').on('click', function() {
        var isValid = true;
        var signup_form = document.getElementById('signup-form');
        signup_form.addEventListener("invalid", function() {
            isValid = false;
        }, true);

        var doSignup = function() {
            if (isValid) {
                var username = $(".nickName").val();
                var password = $("#password1").val();
                var mobile = $(".phone-num").val();
                var captcha = $(".check-phone").val();
                var real_name = $(".realName").val();
                var id_card = $(".idCard").val();
                //组装数据
                var data = {
                    username: username,
                    password: password,
                    mobile: mobile,
                    captcha: captcha,
                    real_name: real_name,
                    id_card: id_card
                }
                $.ajax({
                    url: "http://mobile.goamob.com/index.php/User/reg?act=reg",
                    method: "post",
                    dataType: 'json',
                    data: data,
                    success: function(data) {
                        //注册成功
                        if (data.code === "0") {
                            $('.signup-alert-success').css('display', 'block').next().css('display', 'none');
                            $("#signin-li>a").click();
                        }
                        //注册失败
                        if (data.code === "1") {
                            $('.signup-alert-danger').text(data.message);
                            $('.signup-alert-danger').css('display', 'block').prev().css('display', 'none');
                        }
                    }
                });
            } else {
                // alert('表单信息错误');
            }

        };
        setTimeout(doSignup, 0);
    });
    //登陆
    $(".btnLogin").on("click", function() {

        var isValid = true;
        var login_form = document.getElementById('loginform');
        login_form.addEventListener("invalid", function() {
            isValid = false;
        }, true);

        var doLogin = function() {
            if (isValid) {
                var password = $("#login-password").val();
                var mobile = $("#login-phone").val();
                var remember = $("#remenber").prop('checked');
                //组装数据
                var data = {
                    password: password,
                    mobile: mobile,
                    remember: remember
                }
                $.ajax({
                    url: "http://mobile.goamob.com/index.php/User/login",
                    method: "post",
                    dataType: 'json',
                    data: data,
                    success: function(data) {
                        if (data.code === '0') {
                            $('.login-alert-success').css('display', 'block').next().css('display', 'none');
                            $('#loginClose').click();
                            $('#signin-button').css('display', 'none');
                            $('#user-menu').css('display', 'block');
                        }
                        //登录失败
                        if (data.code === "1") {
                            $('.login-alert-danger').text(data.message);
                            $('.login-alert-danger').css('display', 'block').prev().css('display', 'none');

                        }
                    },
                    error: function() {
                        console.log("error");
                    }
                });
            } else {
                // alert('表单信息错误');
            }

        };
        setTimeout(doLogin, 0);

    });
    //退出登录
    $('#logout').on('click', function() {
        $.ajax({
            url: 'http://mobile.goamob.com/index.php/User/logout',
            dataType: 'json',
            method: 'get',
            success: function(data) {
                console.log(data);
                if (data.code === 0) {
                    console.log(data.message);
                    $('#user-menu').css('display', 'none');
                    $('#signin-button').css('display', 'block');
                } else {
                    console.log(data.code);
                }

            }
        });

    });
    //上传图片
    $("#submitImg").on("click", function() {
        $("#errMsg").html("正在提交...");
        $("#formErr").hide();
        $('#imgform').ajaxForm({
            beforeSubmit: function(formData, jqForm, options) {
                var imgTitle = $("#img-title").val();
                if (imgTitle == "") {
                    $("#errMsg").html("图片标题不能为空！");
                    return false;
                }
                var imgDescription = $("#imgDescription").val();
                if (imgDescription == "") {
                    $("#errMsg").html("图片描述不能为空！");
                    return false;
                }
                var imgUrl = $("#input-file").val();
                if (imgUrl == "") {
                    $("#errMsg").html("图片不能为空！");
                    return false;
                }
                /*var publishImg = $("#publish-img");
                $("input-file").onchange = function(){
                    publishImg.attr("src",$("input-file").val());
                }
                publishImg.onreadystatechange = function(){
                    if(publish-img.readyState == "complete"){
                        checkSize();
                    }
                }
                function checkSize(){
                   var limit =  500 * 1024;
                   if(publishImg.fileSize > limit){
                    $("#errMsg").html("图片不能超过 2 M，请重新选择图片！");
                   }
                }*/
                $("#submitImg").attr("disabled", true);
            },
            success: function(data) {
                if (data.code === 0) {
                    document.getElementsByClassName('publishReset')[0].reset();
                    $("#publish-img").attr("src", "");
                    $("#errMsg").html("");
                    $("#publishClose").click();
                    $("#publishSuccess").fadeIn(1000);
                    setTimeout(function() {
                        $("#publishSuccess").fadeOut(1000);
                    }, 1000);
                    $("#formErr").hide();
                    $("#submitImg").attr("disabled", false);

                } else {
                    $("#formErr").html(data.msg);
                    $("#formErr").show();
                    $("#errMsg").hide();
                    $("#submitImg").attr("disabled", false);
                }

            },
            error: function() {
                $("#formErr").show();
                $("#submitImg").attr("disabled", false);
            }
        });
    });
    $("#publishClose").on("click", function() {
        $("#imgform").clearForm();
        $("#publish-img").attr("src", "");
        $("#formErr").html("");
        $("#errMsg").html("");
    });

    $('.btnLogin').on('mousedown', function(){
        $(this).css('outline','none');
    });

    //上传头像
    $("#submitHeadpic").on("click", function() {
        $("#headpicerrMsg").html("正在提交...");
        $("#headpicformErr").hide();
        $('#headpicform').ajaxForm({
            beforeSubmit: function(formData, jqForm, options) {
                var imgUrl = $("#input-headpic").val();
                if (imgUrl == "") {
                    $("#headpicerrMsg").html("图片不能为空！");
                    return false;
                }
                $("#submitHeadpic").attr("disabled", true);
            },
            success: function(data) {
                if (data.code === 0) {
                    document.getElementsByClassName('publishReset')[0].reset();
                    $("#headpicerrMsg").html("");
                    $("#headpicClose").click();
                    $("#publishSuccess").fadeIn(1000);
                    setTimeout(function() {
                        $("#publishSuccess").fadeOut(1000);
                    }, 1000);
                    $("#headpicformErr").hide();
                    $("#submitHeadpic").attr("disabled", false);

                } else {
                    $("#headpicformErr").html(data.msg);
                    $("#headpicformErr").show();
                    $("#headpicerrMsg").hide();
                    $("#submitHeadpic").attr("disabled", false);
                }

            },
            error: function() {
                $("#headpicformErr").show();
                $("#submitHeadpic").attr("disabled", false);
            }
        });
    });
    $("#headpicClose").on("click", function() {
        $("#headpicform").clearForm();
        $("#headpicformErr").html("");
        $("#headpicerrMsg").html("");
    });

    //朋友搜索
    var searchFriend = $('.searchfriend');
    var searchSelect = $('.search-select');
    var searchResult = document.getElementsByClassName('search-result');
    var $searchResult = $(searchResult);
    var searchNone = $('.search-none');
    var searching = $('.searching');
    var baseUserUrl = "http://mobile.goamob.com/index.php/Community/center/id/";
    searchFriend.bind('input propertychange', function() {  
        searchSelect.slideDown('fast');
        searchNone.hide();
        searching.show();
        var searchVal = $(this).val();
        var data = {
            username: searchVal
        }
        $.ajax({
            url: 'http://mobile.goamob.com/index.php/Community/search',
            method: 'get',
            dataType: 'json',
            data: data,
            beforeSend: function() {
                $searchResult.hide();
            },
            success: function(data) {
                var users = data.data;
                console.log(users);
                searching.hide();
                if(!users) {
                    searchNone.show();
                    $searchResult.hide();
                } else if(users.length > 0){
                    searchNone.hide();
                    for(var i = 0;i < users.length;i++) {
                        $($searchResult[i]).children().text(users[i].username);
                        $($searchResult[i]).children().prop('href', baseUserUrl + users[i].user_id.toString());
                        console.log($($searchResult[i]).children().prop('href'));
                        $($searchResult[i]).show();
                    }
                } else {
                    searchNone.show();
                }
                
            }
        });
    });
    $('.cancel-search').on('click', function() {
        searchSelect.slideUp('fast');
    });

    //修改密码页面
    // var footerH = $('.foot').height();
    // console.log(footerH);
    var oHeight = $(window).height();
    // console.log(oHeight);
    $('.change-pw-page').css('height',oHeight-135);
    $('#getCheckNum').on('click', function(){
        //获取验证码
        var isValid = true;
        var applyForm = document.getElementById('apply-to-change-pw-form');
        

        
    });
    $('#apply-to-change').on('click', function() {
        var isValid = true;
        var applyForm = document.getElementById('apply-to-change-pw-form');
        applyForm.addEventListener('invalid', function() {
            isValid = false;
        }, true);
        var applyToChange = function() {
            if(isValid) {
                $('.apply-change-pw-danger').css('display', 'none');
                $('#apply-to-change-pw-form').css('display','none').next('#change-pw-form').css('display','block');

            } else {
                $('.apply-change-pw-danger').css('display', 'block');
            }
        };
        setTimeout(applyToChange, 0);
    });
    $('#confirm-change').on('click', function() {
        var isValid = true;
        var changeForm = document.getElementById('change-pw-form');
        changeForm.addEventListener('invalid', function() {
            isValid = false;
        }, true);
        var confirmToChange = function() {
            if(isValid) {
                $('.change-pw-danger').css('display','none').prev('.change-pw-success').css('display','block');
            } else {
                $('.change-pw-danger').css('display','block').prev('.change-pw-success').css('display','none');
            }
        };
        setTimeout(confirmToChange, 0);
    });
    $('#change-pw-login').on('click', function() {
        $('#signin-button').click();
        $('#signin-li').click();
    });
});